package com.mkh.st.common.data.datascope;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.mkh.st.common.security.util.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * mybatis entity后置添加
 *
 * @Author: pc
 * @CreateDate: 2021/7/24 13:08
 */
public class MyBatisMetaObjectHandler implements MetaObjectHandler {

	//插入时
	@Override
	public void insertFill(MetaObject metaObject) {
		if (SecurityUtils.getUser() == null) {
			return;
		}
		if (getFieldValByName("createBy", metaObject) == null) {
			setFieldValByName("createBy", SecurityUtils.getUser().getUsername(), metaObject);
		}
		if (getFieldValByName("tenantId", metaObject) == null) {
			setFieldValByName("tenantId", SecurityUtils.getUser().getTenantId(), metaObject);
		}
		if (getFieldValByName("createTime", metaObject) == null) {
			setFieldValByName("createTime", LocalDateTime.now(), metaObject);
		}
	}

	/**
	 *
	 * 更新时
	 * @param metaObject
	 */
	@Override
	public void updateFill(MetaObject metaObject) {
		if (getFieldValByName("updateBy", metaObject) == null) {
			setFieldValByName("updateBy",  SecurityUtils.getUser().getUsername(), metaObject);
		}
		if (getFieldValByName("updateTime", metaObject) == null) {
			setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
		}
	}
}
